// SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
// SPDX-License-Identifier: MIT

package server

import (
	"fmt"
	"net/http"
	"time"

	"uos_uwsgi_exporter/internal/config"
	"uos_uwsgi_exporter/internal/exporter"
	"uos_uwsgi_exporter/pkg/ratelimit"
)

// Server HTTP服务器
type Server struct {
	*http.Server
	exporter *exporter.Exporter
}

// New 创建新的HTTP服务器
func New(cfg *config.Config) *Server {
	// 创建导出器
	exp := exporter.New(cfg)

	// 创建路由器
	mux := http.NewServeMux()

	// 设置路由
	mux.HandleFunc("/", handleLandingPage)
	mux.HandleFunc("/healthz", handleHealthCheck)
	mux.HandleFunc(cfg.MetricsPath, exp.HandleMetrics)

	// 创建服务器
	srv := &http.Server{
		Addr:         fmt.Sprintf("%s:%d", cfg.Address, cfg.Port),
		Handler:      mux,
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 30 * time.Second,
		IdleTimeout:  60 * time.Second,
	}

	// 添加限流中间件
	if cfg.RateLimit > 0 {
		limiter := ratelimit.New(cfg.RateLimit)
		srv.Handler = limiter.Middleware(srv.Handler)
	}

	return &Server{
		Server:   srv,
		exporter: exp,
	}
}

// handleLandingPage 处理着陆页
func handleLandingPage(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(http.StatusOK)

	html := `<!DOCTYPE html>
<html>
<head>
    <title>uWSGI Exporter</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; background-color: #f8f9fa; }
        .container { max-width: 1000px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        h1 { color: #2c3e50; text-align: center; margin-bottom: 30px; }
        h2 { color: #34495e; border-bottom: 2px solid #3498db; padding-bottom: 10px; margin-top: 30px; }
        .endpoint { background: #ecf0f1; padding: 15px; margin: 15px 0; border-radius: 8px; border-left: 4px solid #3498db; }
        .endpoint a { color: #2980b9; text-decoration: none; font-weight: bold; }
        .endpoint a:hover { color: #1f5f8b; text-decoration: underline; }
        .metrics-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin: 20px 0; }
        .metric-category { background: #f8f9fa; padding: 20px; border-radius: 8px; border: 1px solid #dee2e6; }
        .metric-category h3 { color: #495057; margin-top: 0; }
        .metric-list { list-style: none; padding: 0; }
        .metric-list li { padding: 8px 0; border-bottom: 1px solid #e9ecef; }
        .metric-list li:last-child { border-bottom: none; }
        .metric-name { font-family: monospace; color: #6c757d; font-size: 0.9em; }
        .metric-desc { color: #495057; margin-left: 10px; }
        .status { text-align: center; margin: 20px 0; }
        .status-ok { color: #28a745; font-weight: bold; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🚀 uWSGI Exporter</h1>
        <p style="text-align: center; color: #6c757d; font-size: 1.1em;">这是一个用于监控uWSGI应用服务器的Prometheus导出器，提供全面的性能指标监控。</p>
        
        <div class="status">
            <span class="status-ok">✅ 服务运行正常</span>
        </div>
        
        <div class="endpoint">
            <strong>📊 指标端点:</strong> <a href="/metrics">/metrics</a>
            <br><small>Prometheus格式的监控指标</small>
        </div>
        
        <div class="endpoint">
            <strong>❤️ 健康检查:</strong> <a href="/healthz">/healthz</a>
            <br><small>服务健康状态检查</small>
        </div>
        
        <h2>📈 收集的指标</h2>
        
        <div class="metrics-grid">
            <div class="metric-category">
                <h3>🔧 基础指标</h3>
                <ul class="metric-list">
                    <li><span class="metric-name">uwsgi_listen_queue</span><br><span class="metric-desc">监听队列长度</span></li>
                    <li><span class="metric-name">uwsgi_listen_queue_errors</span><br><span class="metric-desc">监听队列错误数</span></li>
                    <li><span class="metric-name">uwsgi_signal_queue</span><br><span class="metric-desc">信号队列长度</span></li>
                    <li><span class="metric-name">uwsgi_load</span><br><span class="metric-desc">系统负载</span></li>
                    <li><span class="metric-name">uwsgi_pid</span><br><span class="metric-desc">主进程PID</span></li>
                    <li><span class="metric-name">uwsgi_cores</span><br><span class="metric-desc">CPU核心数</span></li>
                </ul>
            </div>
            
            <div class="metric-category">
                <h3>👷 Worker指标</h3>
                <ul class="metric-list">
                    <li><span class="metric-name">uwsgi_worker_requests</span><br><span class="metric-desc">处理的请求数</span></li>
                    <li><span class="metric-name">uwsgi_worker_exceptions</span><br><span class="metric-desc">异常数</span></li>
                    <li><span class="metric-name">uwsgi_worker_status</span><br><span class="metric-desc">运行状态</span></li>
                    <li><span class="metric-name">uwsgi_worker_rss</span><br><span class="metric-desc">RSS内存使用量</span></li>
                    <li><span class="metric-name">uwsgi_worker_vsz</span><br><span class="metric-desc">VSZ内存使用量</span></li>
                    <li><span class="metric-name">uwsgi_worker_avg_rt</span><br><span class="metric-desc">平均响应时间</span></li>
                    <li><span class="metric-name">uwsgi_worker_respawn_count</span><br><span class="metric-desc">重启次数</span></li>
                </ul>
            </div>
            
            <div class="metric-category">
                <h3>📱 应用指标</h3>
                <ul class="metric-list">
                    <li><span class="metric-name">uwsgi_app_requests</span><br><span class="metric-desc">应用请求数</span></li>
                    <li><span class="metric-name">uwsgi_app_exceptions</span><br><span class="metric-desc">应用异常数</span></li>
                    <li><span class="metric-name">uwsgi_app_startup_time</span><br><span class="metric-desc">启动时间</span></li>
                    <li><span class="metric-name">uwsgi_app_master_pid</span><br><span class="metric-desc">主进程PID</span></li>
                    <li><span class="metric-name">uwsgi_app_worker_pid</span><br><span class="metric-desc">Worker进程PID</span></li>
                </ul>
            </div>
            
            <div class="metric-category">
                <h3>💾 缓存指标</h3>
                <ul class="metric-list">
                    <li><span class="metric-name">uwsgi_cache_keys</span><br><span class="metric-desc">缓存键数量</span></li>
                    <li><span class="metric-name">uwsgi_cache_hits</span><br><span class="metric-desc">缓存命中数</span></li>
                    <li><span class="metric-name">uwsgi_cache_misses</span><br><span class="metric-desc">缓存未命中数</span></li>
                </ul>
            </div>
            
            <div class="metric-category">
                <h3>🔒 锁指标</h3>
                <ul class="metric-list">
                    <li><span class="metric-name">uwsgi_locks_count</span><br><span class="metric-desc">锁数量</span></li>
                </ul>
            </div>
            
            <div class="metric-category">
                <h3>🌐 连接指标</h3>
                <ul class="metric-list">
                    <li><span class="metric-name">uwsgi_connection_errors</span><br><span class="metric-desc">连接错误数</span></li>
                    <li><span class="metric-name">uwsgi_connection_timeout</span><br><span class="metric-desc">连接超时数</span></li>
                </ul>
            </div>
        </div>
        
        <div style="margin-top: 30px; padding: 20px; background: #e3f2fd; border-radius: 8px; border-left: 4px solid #2196f3;">
            <h3 style="margin-top: 0; color: #1976d2;">💡 使用说明</h3>
            <p style="margin-bottom: 10px;"><strong>配置uWSGI:</strong> 确保uWSGI启用了stats socket或HTTP统计接口</p>
            <p style="margin-bottom: 10px;"><strong>Prometheus配置:</strong> 添加此exporter到Prometheus的scrape_configs</p>
            <p style="margin-bottom: 0;"><strong>Grafana:</strong> 使用收集的指标创建监控仪表板</p>
        </div>
    </div>
</body>
</html>`

	w.Write([]byte(html))
}

// handleHealthCheck 处理健康检查
func handleHealthCheck(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)

	response := `{"status":"ok","timestamp":"` + time.Now().Format(time.RFC3339) + `"}`
	w.Write([]byte(response))
}
